"use strict";
const fs = require("fs");
const request = require("request");

const generalGetFnForHandleFeedback = function(success, fail, customCheck, customErr) {
	return function(e, res, body) {
		if (e) {
			console.error("网络错误", e, e.stack);
			fail(e);
			return;
		}
		console.log("服务器返回的数据是", body);
		if (!customCheck(body)) {
			const error = customErr || new Error("server_response_fail");
			error.additionalData = body;
			fail(error);
			return;
		}
		success(body);
	};
};

const getFnForHandleFeedback = function(success, fail, customErr) {
	const check = function(body) {
		if (body.status !== 0) {
			console.error("服务器返回码非0");
			return false
		}
		return true;
	};
	return generalGetFnForHandleFeedback(success, fail, check, customErr);
};

const getFnForHandleAdminServerFeedback = function(success, fail, customErr) {
	const check = function(body) {
		if (body.hasErrors === true) {
			console.error("调用管理后台api出错", body);
			return false
		}
		return true;
	};
	return generalGetFnForHandleFeedback(success, fail, check, customErr);
};

const getHeaders = function(param) {
	return {
		"Accept": "application/json",
		"X-ACCESS-KEY": param.key,
		"X-ACCESS-TIMESTAMP": param.time,
		"X-ACCESS-TOKEN": param.token
	};
};

const getFormData = function(file) {
	return {
		file: {
			value: fs.createReadStream(file.path),
			options: {
				filename: file.name,
				contentType: file.contentType
			}
		}
	};
};

const inspect = function(obj, deep) {
	return require("util").inspect(obj, {
		depth: deep || null
	});
};

const removeTailSlash = function(url) {
	if (!url) {
		return url;
	} else {
		return url.replace(new RegExp("/+$"), "");
	}
};
const getFileExtension = function(fileName) {
	const reg = /[^.]+$/;
	const result = fileName.match(reg);
	if (result === null) {
		return null;
	} else {
		return result[0];
	}
};

const sendRequest = function(options) {
	return new Promise((success, fail) => {
		request(options, getFnForHandleFeedback(success, fail));
	});
};

const sendRequestToAdminServer = function(options) { //操蛋的管理后台返回信息跟其它人都不相同
	return new Promise((success, fail) => {
		request(options, getFnForHandleAdminServerFeedback(success, fail));
	});
};

module.exports = {
	getFnForHandleFeedback,
	getHeaders,
	getFormData,
	inspect,
	removeTailSlash,
	getFileExtension,
	sendRequest,
	sendRequestToAdminServer
};